package com.woniuxy.factory.service.imp;

import com.woniuxy.factory.entity.Purchasegoods;
import com.woniuxy.factory.entity.Purchaseplan;
import com.woniuxy.factory.entity.ResponseResult;
import com.woniuxy.factory.exception.BusinessException;
import com.woniuxy.factory.mapper.PurchasegoodsMapper;
import com.woniuxy.factory.mapper.PurchaseplanMapper;
import com.woniuxy.factory.service.PurchasegoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PurchasegoodsServiceImp implements PurchasegoodsService {
    @Autowired
    PurchasegoodsMapper purchasegoodsMapper;
    @Autowired
    PurchaseplanMapper purchaseplanMapper;

    @Override
    public ResponseResult<List<Purchasegoods>> getPurchasegoodsById(Purchaseplan purchaseplan, int page, int limit) {
        //插叙记录条数
        int count = purchasegoodsMapper.getCount(purchaseplan);
        int home = (page-1)*limit;
        List<Purchasegoods>  purchasegoods= purchasegoodsMapper.selectPurchasegoods(purchaseplan,home,limit);
        return new ResponseResult<>(0,"查询成功",count,purchasegoods);
    }
    //新增采购计划项
    @Override
    public ResponseResult addPurchasegood(String pupId, String matId, int quantity) {
        //查询采购记录状态是否合法
        Purchaseplan purchaseplan = new Purchaseplan();
        purchaseplan.setPupId(pupId);
        List<Purchaseplan> purchaseplans = purchaseplanMapper.selectPurchaseplans(purchaseplan, 0, 3);
        try {
            if (purchaseplans.get(0).getApplicationRecord().getApplystatus()!=0) {
                return new ResponseResult(1,"采购计划已审批不能添加",null,null);
            }
        }catch (NullPointerException e){
            return new ResponseResult(1,"采购计划不存在",null,null);
        }
        int num = purchasegoodsMapper.insertPurchaseGoods(pupId,matId,quantity);
        if (num==0){
            return new ResponseResult(1,"新增失败",null,null);
        }
        return new ResponseResult(0,"新增成功",null,null);
    }

    @Override
    public ResponseResult deletepurchaseplangoods(int[] pugIds) {
        int i = purchasegoodsMapper.deletepurchaseplangoods(pugIds);
        if (i==0){
            throw new BusinessException("删除失败");
        }
        return new ResponseResult(0,"删除成功",null,null);
    }
}
